<?php
/**
 * Content
 * 
 */
class ContentChunks{

	const admin_menu_slug = 'content_chunks';
	const default_shortcode_name = 'get_chunks';
	const option_key = 'content_chunks_shortcode';
	/**
	 * 
	 */
	public static function register_chunk_post_type()
	{
		register_post_type(
			'chunk',
			array(
				'label' => 'Chunks',
				'labels' => array(
					'add_new' => 'Add New',
					'add_new_item' => 'Add New Chunk',
					'edit_item' => 'Edit Chunk',
					'new_item' => 'New Chunk',
					'view_item' => 'View Chunk',
					'search_items' => 'Search Chunks',
					'not_found' => 'No Chunks Found',
					'not_found_in_trash' => 'Not Found in Trash',
				),
				'description' => 'Reusable chunks of content',
				'public' => true,
				'show_ui' => true,
				'menu_position' => 5,
				'supports' => array(
					'title',
					'editor',
				),
			)
		);
		add_theme_support('post-thumbnails', array('chunk'));
	}
	
	/**
	 * register short code
	 */
	public static function register_shortcodes(){
		$shortcode = get_option(self::option_key,self::default_shortcode_name);
		add_shortcode($shortcode, 'ContentChunks::get_chunk');
	}
	
	/**
	 * returns chunks via shortcode
	 * 
	 * @param	array	$raw_args	arguments
	 * @param	string	$content	optional content
	 * @return	string	text replace shortcode
	 */
	public static function get_chunk($raw_args,$content=null)
	{
		$defaults = array(
			'title' => '',
		);
		$sanitized_args = shortcode_atts($defaults, $raw_args);
		if (empty($sanitized_args['title'])) 
		{
			return '';
		}
		$result = get_page_by_title($sanitized_args['title'], 'OBJECT', 'chunk');
		if ($result) 
		{
			return $result->post_content;
		}
	}
	
	/**
	 * create custom menu
	 */
	public static function create_admin_menu()
	{
		add_menu_page(
			'Content Chunks',
			'Content Chunks',
			'manage_options',
			self::admin_menu_slug,
			'ContentChunks::get_admin_page'
		);
	}
	
	/**
	 * print admin page
	 */
	public static function get_admin_page()
	{
		if (!empty($_POST)&&check_admin_referer('content_chunks_options_update','content_chunks_admin_nonce')) 
		{
			update_option(self::option_key,stripslashes($_POST['shortcode_name']));
			$msg = '<div class="updated"><p>Your settings have been <strong>updated</strong></p></div>';
		}
		$shortcode_name = esc_attr(get_option(self::option_key,self::default_shortcode_name));
		include('admin_page.php');
	}
	
	/**
	 * 
	 * @param	array	$links	- a hash nama => translation
	 * @param	string	$file	- path plugin's main file from plugins dir
	 * @return	array	the $link hash
	 */
	public static function add_plugin_settings_link($link, $file)
	{
		if ($file == 'content-chunks/index.php') 
		{
			$settings_link = sprintf('<a href="%s">%s</a>', 
				admin_url('options-general.php?page='.self::admin_menu_slug),
				'Settings'
			);
			array_unshift($link,$settings_link);
		}
		return $link;
	}
}

/* EOF */
 
